/**
 * @Author: Bobby
 * @Date: 2021-11-08 15:20:01
 * @LastEditTime: 2022-03-23 09:18:45
 * @LastEditors: Bobby
 * @Description: 路由守卫，目前两种模式：all模式与intelligence模式
 * @FilePath: \wms-v2\src\vui\plugins\permissions.js
 * @CIMC-V2
 */
import { setStorage, getStorage } from '@/utils/tools'
import store from '@commonProject/store'
import router from '@commonProject/router'

import VuiProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/pageTitle'
import { toLoginRoute, toAppsRoute } from '@/utils/routes'
import { authentication, loginInterception, routesWhiteList, supportVisit, toAppsPage, independent, loginCenter } from '@project/config'

export function setup() {
  VuiProgress.configure({
    easing: 'ease',
    speed: 500,
    trickleSpeed: 200,
    showSpinner: false,
  })

  router.beforeEach(async (to, from, next) => {
    if (to.query['clear'] === 'true') {
      console.log('调用resetAll -2')
      await store.dispatch('user/resetAll', {
        clear: false,
        toLoginUrl: true,
      })
    }
    // debugger
    const { showProgressBar } = store.getters['settings/theme']
    if (showProgressBar) VuiProgress.start()
    let hasToken = store.getters['user/token']
    if (!loginInterception) hasToken = true
    //是否有token
    if (hasToken) {
      if (store.getters['routes/routes'].length) {
        let _BuildProject = process.env.VUE_APP_BuildProject
        // menu界面及时更新
        if (to.path == '/menu' && _BuildProject == 'pda') {
          console.log('from', from.fullPath == '/apps')
          // 只有apps界面来menu界面的时候需要重置token（以及pc跳转pda得时候需要重置token）
          await store.dispatch(
            'user/getUserInfo',
            from.fullPath == '/apps' && to.path == '/menu'
              ? { ...store.getters['user/businessCode'], token_reset: 'Y' }
              : { ...store.getters['user/businessCode'] }
          )
        }
        // 禁止已登录用户返回登录页
        if (to.path === '/login') {
          next({ path: '/' })
          if (showProgressBar) VuiProgress.done()
        } else next()
      } else {
        let hasAppId = store.getters['user/appId']
        // 如果不使用to apps 请在config设置false
        if (!toAppsPage) {
          hasAppId = true
        }
        if (hasAppId) {
          try {
            let _BuildProject = process.env.VUE_APP_BuildProject
            if (loginInterception && to.path !== '/apps' && to.path !== '/toapp' && _BuildProject != 'login') {
              await store.dispatch(
                'user/getUserInfo',
                from.fullPath == '/apps' && to.path == '/menu'
                  ? { ...store.getters['user/businessCode'], token_reset: 'Y' }
                  : { ...store.getters['user/businessCode'] }
              )
            }
            //loginCenter || !independent
            if (loginCenter) {
              //执行跳转到app
              // store.dispatch('user/toApp')
              if (to.path !== '/apps') {
                next(toAppsRoute(to.path))
              } else {
                next()
              }
            } else {
              // 根据路由模式获取路由并根据权限过滤
              await store.dispatch('routes/setRoutes', authentication)
              next({ ...to, replace: true })
            }
          } catch (err) {
            let _errorNum = getStorage('ErrorNum')
            console.error('错误拦截:', err.message, _errorNum)
            if (_errorNum) {
              _errorNum++
              setStorage('ErrorNum', _errorNum)
            } else {
              setStorage('ErrorNum', 1)
            }

            // 登出
            // if (independent) {
            //   next(toLoginRoute(to.path))
            // } else {
            //   await store.dispatch('user/resetAll', {clear: true})
            //   next()
            // }
          }
        } else {
          if (to.path !== '/apps' && to.path !== '/menu') {
            next(toAppsRoute(to.path))
          } else if (to.path == '/menu') {
            next()
          } else {
            next()
          }
        }
      }
    } else {
      if (routesWhiteList.includes(to.path)) {
        // 设置游客路由(可删除)
        if (supportVisit && !store.getters['routes/routes'].length) {
          await store.dispatch('routes/setRoutes', 'visit')
          next({ path: to.path, replace: true })
        } else next()
      } else {
        if (independent) {
          next(toLoginRoute(to.path))
        } else {
          console.log('调用resetAll -3')
          await store.dispatch('user/resetAll', {
            clear: true,
            toLoginUrl: true,
          })
          next()
        }
      }
    }
  })
  router.afterEach((to) => {
    document.title = getPageTitle(to.meta.title)
    if (VuiProgress.status) VuiProgress.done()
  })
}
